package com.ruanda.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruanda.domain.SysUser;
import com.ruanda.domain.SysUserRole;
import com.ruanda.mapper.SysUserMapper;
import com.ruanda.mapper.SysUserRoleMapper;
import com.ruanda.service.SysUserRoleService;
import com.ruanda.service.SysUserService;
import com.ruanda.util.AuthUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 亦樂
* @description 针对表【sys_user(系统用户)】的数据库操作Service实现
* @createDate 2024-09-03 16:41:33
*/
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
    implements SysUserService{

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer saveSysUser(SysUser sysUser) {
        // 补充管理员对象属性的值
        sysUser.setCreateUserId(AuthUtils.getLoginUserId());
        sysUser.setCreateTime(new Date());
        sysUser.setStatus(1);
        // 默认平台统一一个店铺
        sysUser.setShopId(1L);
        // 获取管理员密码
        String password = sysUser.getPassword();
        // 判断是否有值
        if (StringUtils.hasText(password)) {
            // 管理员密码使用 加密
            sysUser.setPassword(passwordEncoder.encode(password));
        }
        // 新增管理员
        int count = sysUserMapper.insert(sysUser);
        if (count > 0) {
            // 获取新增管理员id
            Long userId = sysUser.getUserId();
            // 获取管理员角色id集合
            List<Long> roleIdList = sysUser.getRoleIdList();
            // 判断角色id集合是否有值
            if (!CollectionUtils.isEmpty(roleIdList) && roleIdList.size() != 0) {
                // 创建管理员与角色关系集合对象
                List<SysUserRole> sysUserRoleList = new ArrayList<>();
                // 循环遍历角色id集合
                roleIdList.forEach(roleId -> {
                    // 创建管理员与角色关系对象
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(userId);
                    sysUserRole.setRoleId(roleId);
                    // 将管理员与角色关系对象添加到管理员与角色关系集合中
                    sysUserRoleList.add(sysUserRole);
                });
                // 批量添加 管理员与角色关系集合
                sysUserRoleService.saveBatch(sysUserRoleList);
            }
        }
        return count;
    }

    @Override
    public SysUser querySysUserDetailByUserId(Long userId) {
        // 根据管理员ID查询管理员详情
        SysUser sysUser = sysUserMapper.selectById(userId);
        // 根据管理员ID查询管理员与角色关系集合
        List<SysUserRole> sysUserRoleList = sysUserRoleMapper.selectList(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, userId)
        );
        // 判断管理员与角色关系集合是否有值
        if (!CollectionUtils.isEmpty(sysUserRoleList) && sysUserRoleList.size() != 0) {
            // 从管理员与角色关系集合中获取角色ID集合
            List<Long> roleIdList = sysUserRoleList.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
            sysUser.setRoleIdList(roleIdList);
        }
        return sysUser;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer modifySysUser(SysUser addOrUpdateParam) {
        // 获取管理员ID
        Long userId = addOrUpdateParam.getUserId();
        // 删除管理员原有的角色
        sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId,userId)
        );
        // 获取管理员角色id集合
        List<Long> roleIdList = addOrUpdateParam.getRoleIdList();
        // 判断角色id集合是否有值
        if (!CollectionUtils.isEmpty(roleIdList) && roleIdList.size() != 0) {
            // 创建管理员与角色关系集合对象
            List<SysUserRole> sysUserRoleList = new ArrayList<>();
            // 循环遍历角色id集合
            roleIdList.forEach(roleId -> {
                // 创建管理员与角色关系对象
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(userId);
                sysUserRole.setRoleId(roleId);
                // 将管理员与角色关系对象添加到管理员与角色关系集合中
                sysUserRoleList.add(sysUserRole);
            });
            // 批量添加 管理员与角色关系集合
            sysUserRoleService.saveBatch(sysUserRoleList);
        }
        // 获取管理员新密码
        String newPassword = addOrUpdateParam.getPassword();
        // 判断新密码是否有值，如果有值：设置新密码，相反：密码不变
        if (StringUtils.hasText(newPassword)) {
            // 新密码加密
            String encodeNewPassword = passwordEncoder.encode(newPassword);
            addOrUpdateParam.setPassword(encodeNewPassword);
        }
        return sysUserMapper.updateById(addOrUpdateParam);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer removeSysUsersByUserIdList(List<Long> userIds) {
        // 批量删除指定管理员与角色的关系记录
        sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                .in(SysUserRole::getUserId,userIds)
        );
        // 批量删除指定管理员
        return sysUserMapper.deleteBatchIds(userIds);
    }
}




